<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入单据号/姓名/手机号/案件名称"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-select
            v-model="listQuery.account_type"
            placeholder="银行账号"
            clearable
            size="small"
          >
            <el-option
              v-for="item in banks"
              :label="item.account"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddSale"
            >新增收款单</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="receiptList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="item in tableColumns"
          :label="item.title"
          :prop="item.key"
          :key="item.key"
          :align="item.align ? item.align : 'center'"
          :formatter="dataFormatter"
        ></el-table-column>

        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getReceiptOrders"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="60%">
      <el-form
        :model="receiptForm"
        :rules="receiptFormRules"
        ref="receiptFormRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="单据号"
              prop="order_no"
              v-if="dialogType === 'edit'"
            >
              <el-input
                type="text"
                v-model="receiptForm.order_no"
                placeholder="单据号"
                maxlength="24"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开单时间" prop="order_time">
              <el-date-picker
                v-model="receiptForm.order_time"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择开单时间"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="销售单据号" prop="sale_order">
          <el-select
            v-model="receiptForm.sale_order"
            placeholder="销售单据号"
            clearable
            @change="selectChange"
          >
            <el-option
              v-for="item in sales"
              :key="item.id"
              :label="item.order_no + '--' + item.customer_name"
              :value="item.id"
            >
              <span style="float: left"
                >{{ item.order_no }}[{{ item.customer_name }}]</span
              >
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.case_name
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案件名称" prop="case_name">
          <el-input
            v-model="receiptForm.case_name"
            placeholder="案件名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input
            v-model="receiptForm.telephone"
            placeholder="手机号码"
            clearable
          />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="会计科目" prop="acc_title">
              <el-cascader
                v-model="selectedKeys"
                :options="accountList"
                :props="props"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账号" prop="account_type">
              <el-select
                v-model="receiptForm.account_type"
                placeholder="收款账号"
                clearable
              >
                <el-option
                  v-for="item in banks"
                  :label="item.account"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="应收金额" prop="recv_money">
              <el-input
                v-model="receiptForm.recv_money"
                placeholder="应收金额"
                clearable
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实收金额" prop="paid_money">
              <el-input
                v-model="receiptForm.paid_money"
                placeholder="实收金额"
                clearable
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经办人" prop="handler">
              <el-select
                v-model="receiptForm.handler"
                placeholder="经办人"
                clearable
              >
                <el-option
                  v-for="item in employees"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                v-model="receiptForm.desc"
                placeholder="备注"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveOrder">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import { getEmployeeList } from "@/api/employee";
import {
  getReceipts,
  addReceipt,
  updateReceipt,
  delReceipt,
  getSaleList,
} from "@/api/sale";
import { getBanks } from "@/api/bank";
import { get_account_titles } from "@/api/account";
import { pickerOptions } from "@/utils/const";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  order_no: "",
  order_time: getCurrentDate(),
  sale_order: null,
  case_name: "",
  telephone: "",
  acc_title: null,
  recv_money: 0,
  paid_money: 0,
  account_type: null,
  desc: "",
  handler: null,
  user: null,
};

export default {
  name: "Receipt",

  data() {
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        callback();
      }
    };
    const checkPaidMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        callback();
      }
    };

    return {
      receiptForm: Object.assign({}, defaultForm),
      receiptFormRules: {
        order_time: [
          { required: true, message: "请输入开单时间", trigger: "blur" },
        ],
        sale_order: [
          { required: true, message: "请选择销售单", trigger: "blur" },
        ],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        acc_title: [
          { required: true, message: "请选择会计科目", trigger: "blur" },
        ],
        account_type: [
          { required: true, message: "请选择收款账号", trigger: "blur" },
        ],
        recv_money: [{ validator: checkMoney, trigger: "blur" }],
        paid_money: [{ validator: checkPaidMoney, trigger: "blur" }],
      },
      title: "收款单",
      sales: [],
      accountList: [],
      banks: [],
      employees: [],
      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dialogType: "new",
      receiptList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
        search_date: "",
        account_type: null,
      },
      tableColumns: [
        {
          key: "order_no",
          title: "收款单据号",
        },
        {
          key: "order_time",
          title: "单据日期",
        },
        {
          key: "sale_order_no",
          title: "销售单据号",
        },
        {
          key: "sale_order_name",
          title: "客户名称",
        },
        {
          key: "account_name",
          title: "会计科目",
        },
        {
          key: "acc_type_name",
          title: "收款账号",
        },
        {
          key: "recv_money",
          title: "应收金额(元)",
        },
        {
          key: "paid_money",
          title: "实收金额(元)",
        },
        {
          key: "debt",
          title: "欠款金额(元)",
        },
        {
          key: "handler_name",
          title: "经办人",
        },
      ],
      pickerOptions,
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getReceiptOrders();
    this.getSales();
    this.getAccounts();
    this.getBankList();
    this.getEmployeeList();
  },
  methods: {
    // 销售单列表
    getReceiptOrders() {
      this.listLoading = true;
      getReceipts(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.receiptList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取收款单数据失败");
          this.listLoading = false;
        });
    },
    getSales() {
      getSaleList()
        .then((res) => {
          this.sales = res;
        })
        .catch((error) => {
          this.$message.error("获取销售单数据失败");
          console.log(error.message);
        });
    },
    getAccounts() {
      get_account_titles({}).then((res) => {
        console.log("tree2:", res);
        this.accountList = res;
      });
    },
    getBankList() {
      getBanks().then((res) => {
        this.banks = res;
      });
    },
    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "recv_money" ||
          column.property === "paid_money" ||
          column.property === "debt"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "recv_money") {
        return row.recv_money.toFixed(2);
      } else if (column.property == "paid_money") {
        return row.paid_money.toFixed(2);
      } else if (column.property == "debt") {
        return row.debt.toFixed(2);
      } else {
        return cellValue;
      }
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getReceiptOrders();
    },
    // 增加员工
    handleAddSale() {
      this.receiptForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.receiptFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.receiptForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(
          this.receiptForm.acc_title,
          this.accountList
        );
        this.$refs["receiptFormRef"].clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该收款单吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delReceipt(row.id);

          this.receiptList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("收款单删除失败!");
        });
    },
    // 保存操作
    async SaveOrder() {
      this.$refs.receiptFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.receiptForm.user) {
            this.receiptForm.user = this.uid;
          }
          res = await updateReceipt(this.receiptForm);
          console.log(isEdit, res);
          const index = this.receiptList.findIndex((v) => v.id === res.id);
          this.receiptList.splice(index, 1, res);
        } else {
          this.receiptForm.user = this.uid;
          res = await addReceipt(this.receiptForm);
          const { id } = res;
          if (id > 0) {
            this.getReceiptOrders();
          }
        }

        const {
          order_no,
          sale_order_name,
          telephone,
          recv_money,
          paid_money,
          account_name,
        } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${order_no}</div>
              <div>客户名称: ${sale_order_name}</div>
              <div>手机号: ${telephone}</div>
              <div>应收金额: ${recv_money}</div>
              <div>实收金额: ${paid_money}</div>
              <div>会计科目: ${account_name}</div>
            `,
          type: "success",
        });
      });
    },
    handleChange(value) {
      console.log("selectedKeys:", this.selectedKeys);
      if (this.selectedKeys.length > 0) {
        this.receiptForm.acc_title = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
      } else {
        this.receiptForm.acc_title = undefined;
      }
    },
    selectChange(value) {
      console.log("selectChange:", value);
      const sale = this.sales.find((v) => v.id == value);
      this.receiptForm.telephone = sale.telephone;
      this.receiptForm.recv_money = sale.debt;
      this.receiptForm.case_name = sale.case_name;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select {
    width: 100%;
  }
  .item {
    margin-top: 8px;
  }
}
</style>